<?
/**
 * Router
 */
class Router {
    
    protected $routes;
    
    public function __construct($debug=false){
        $routes = Spyc::YAMLLoad(ROUTING_FILE);
        if(isset($routes["includes"]) && $routes["includes"] != ""){
        	foreach($routes["includes"] as $file){
        		$routes = array_merge($routes,Spyc::YAMLLoad(ROUTES_DIR.$file));
        	}
        }
        $find = false;
        $aUrlVars = array();
        
        foreach($routes as $url=>$infos){
            if($debug) echo "$url <br>";
            $aUrl = explode("/",substr($url,1));
            $query = $_SERVER["SCRIPT_URL"];
            $aQuery = explode("/",substr($query,1));
            if(count($aQuery) <> count($aUrl)){
                continue;
            }
           $i=0;
           $ok = false;
           $match = 0;
           while($i < count($aUrl)){
              // check if variable
              if(substr($aUrl[$i],0,1) != "#"){
                  if($aUrl[$i] != $aQuery[$i]){
                      break;
                      $i++;
                  }else{
                     $match++;
                     $i++;
                  }
              }else{
                  $v = substr($aUrl[$i],1);
                  $aUrlVars[$v] = $aQuery[$i];
                  $match++;
                  $i++;
              }
           }
           if($match == count($aUrl)){
              if($debug) echo " Find! <br/>";
              $route = $infos;
           }
        }
        if(empty($route)){
           throw new Exception ("No route found for $query");
       }
       $route["urlParams"] = $aUrlVars;
       $this->route = $route;
       
    }
    public function getRoute(){
        return (object) $this->route;
    }
}